<?php

/**
 * 仓库
 * @author wangwx 2015-5-7
 */
namespace common\repositories\myhtsq;

use common\repositories\BaseRepository;
use common\entities\myhtsq\AuthorizationAchievementEntity;
use common\support\StringHelper;
use common\entities\common\MyscrmOrganizationToAuthorizeEntity;
use common\repositories\common\MyscrmApplicationRepository;
use common\services\common\MyscrmContractApplicationService;



class AuthorizationAchievementRepository extends BaseRepository
{
    /**
     * 构造方法
     * @param unknown $config (optional)
     */
    public function __construct($config = [])
    {
        parent::__construct($config);
    }

    public static function addAuthorizationAchievement($arr,$contract=null)
    {

        $addAchievement = new AuthorizationAchievementEntity();

        $contractModel = ContractManageRepository::getContractManageModelByContractId($arr['contract_id']); //获取model

        $applicationInfo = MyscrmApplicationRepository::getApplicationByApplicationId($arr['application_id']);//租户中心产品

        if(! empty($applicationInfo)){
            $appDataInfo = MyscrmContractApplicationService::getApplicationInfoByAuthorizeUniqueName($applicationInfo->UniqueName);//查真名用
        }

        $arr['application_id'] = empty($appDataInfo)?$arr['application_id']:$appDataInfo['application_id'];

        $arr['settlement_amount'] = empty($arr['settlement_amount'])?0:$arr['settlement_amount'];
        $arr['settlement_average_amount'] = empty($arr['settlement_average_amount'])?0:$arr['settlement_average_amount'];

        $arr['product_average_amount'] = empty($arr['product_average_amount'])?0:$arr['product_average_amount'];
        $arr['sign_average_amount'] = empty($arr['sign_average_amount'])?0:$arr['sign_average_amount'];


        if($arr['__type'] === 'delete' && !empty($arr['id'])){//删除业绩
            $delAchievement = $addAchievement::findOne($arr['id']);
            $delAchievement->is_del = 2;//表示删除
            $res = $delAchievement->save();

            return $res?$delAchievement->attributes['contract_application_id']:false;

        }

        if($arr['__type'] === 'edit' && empty($contract)) {//通过授权修改

            if(!empty($arr['id'])){

                $editAchievement = $addAchievement::find()->where(['author_id'=>$arr['id']])->one();//一定要传author_id 也就是orgtoauthor 的id 为NULL 修改成功是巧合
                if(!$editAchievement){
                    $editAchievement = new AuthorizationAchievementEntity();
                    $editAchievement->author_id = $arr['id'];
                    $editAchievement->id = StringHelper::uuid();
                }

                $priceInfo = ApplicationPriceRepository::getApplicationPriceByApplicationId($arr['application_id']);
                $price = $priceInfo['price'];

                $editAchievement->contract_application_id = $arr['contract_application_id'];
                $editAchievement->contract_id = $arr['contract_id'];

                $editAchievement->contractId = $arr['contractId'];//配置库那个

                $editAchievement->price = $price;
                $editAchievement->authorization_numeric = (int)$arr['total_num'];
                $editAchievement->settlement_type = $arr['settlement_type'];

                $editAchievement->contract_type = $arr['product_type'];
                $editAchievement->settlement_scale = $arr['settlement_scale'];
                $editAchievement->discount = $arr['discount'];
                $editAchievement->rent_period = $arr['rent_period'];

                $editAchievement->amount = (int)$arr['total_num']*$price;//取标准单价计算

                $editAchievement->origin_settlement_average_amount = $arr['settlement_amount'];//原结算分摊金
                $editAchievement->settlement_average_amount = $arr['settlement_amount'];

                $editAchievement->origin_product_average_amount = $arr['product_average_amount'];//原产品分摊金
                $editAchievement->product_average_amount = $arr['product_average_amount'];

                $editAchievement->origin_sign_average_amount = $arr['sign_average_amount'];//原签约分摊金
                $editAchievement->sign_average_amount = $arr['sign_average_amount'];

                $editAchievement->created_type = 1;//手动开通授权产生业绩
                $editAchievement->is_del = 1;//表示新增 记得原来的数据有可能为空预留给他们
                $editAchievement->application_name = $arr['application_name'];//产品名称
                $editAchievement->establish_time = $arr['establish_time'];//开通时间

                $res = $editAchievement->save();

                return $res?$editAchievement->attributes['contract_application_id']:false;

            }


            if(!empty($arr['author_id'])){//租户中管理过来

                if(empty($arr['contract_application_id'])){//云建要加的逻辑 如小蜜蜂
                    return true;
                }


                $priceInfo = ApplicationPriceRepository::getApplicationPriceByApplicationId($arr['application_id']);
                $price = $priceInfo['price'];

                $editAchievement = $addAchievement::find()->where(['author_id'=>$arr['author_id']])->one();//一定要传author_id 也就是orgtoauthor 的id 为NULL 修改成功是巧合

                $contractAndApp = ContractApplicationRepository::getContractApplicationAppId($arr['contract_application_id']);//订单产品信息
                $editAchievement->application_id = $contractAndApp->application_id;

                $editAchievement->contract_id = $arr['contract_id'];

                $editAchievement->authorization_numeric = (int)$arr['total_num'];
                $editAchievement->settlement_type = $arr['settlement_type'];//结算类型
                $editAchievement->settlement_scale = $arr['settlement_scale'];//结算比例
                $editAchievement->discount = $arr['discount'];//结算比例
                $editAchievement->contract_type = $arr['contract_type'];
                $editAchievement->rent_period = $arr['rent_period'];
                $editAchievement->created_type = 2;//自动开通授权产生业绩
                $editAchievement->is_del = 1;//表示新增 记得原来的数据有可能为空预留给他们
                $editAchievement->application_name = $arr['friendly_name'];//产品名称
                //$editAchievement->establish_time = $arr['establish_time'];//开通时间 判断是否为历史数据

                $editAchievement->origin_settlement_average_amount = empty($arr['settlement_from_tenant'])?0:$arr['settlement_from_tenant'];//原结算分摊金

                //租户那边修改后需要维护分摊金
                $editAchievement->settlement_average_amount = empty($arr['settlement_from_tenant'])?0:$arr['settlement_from_tenant'];

                $editAchievement->origin_sign_average_amount = $arr['sign_average_amount'];//原签约分摊金
                $editAchievement->sign_average_amount = $arr['sign_average_amount'];

                $editAchievement->origin_product_average_amount = $arr['product_average_amount'];//原产品分摊金
                $editAchievement->product_average_amount = $arr['product_average_amount'];

                $editAchievement->amount = $price*(int)$arr['total_num'];//计算标准总额
                
                $res = $editAchievement->save();

                return !empty($res)?$editAchievement->attributes['id']:false;

            }

        }


        // 如果$arr['id'] 查询出 establish_time 为null 表示为历史数据需要根据 contract_application_id 修改
        if(!empty($arr['id'])){// 如果有id表示为修改  $arr['id'] = 'ykClass' 表示基本信息更新

            //问题所在注意调整前端有显示校验会导致数据库与结果不一致
            $editAchievement = $addAchievement::findOne($arr['id']);
            $editAchievement->rent_period = $arr['rent_period'];//租用周期
            $editAchievement->contract_type = $arr['contract_type'];//合同属性
            $editAchievement->authorization_numeric = $arr['authorization_numeric'];//产品数
            $editAchievement->settlement_type = $arr['settlement_type'];//结算类型
            $editAchievement->settlement_scale = $arr['settlement_scale'];//结算比例
            $editAchievement->discount = $arr['discount'];//结算比例

            $editAchievement->origin_settlement_average_amount = $arr['origin_settlement_average_amount'];//原结算分摊金额
            $editAchievement->adjust_settlement_average_amount = $arr['adjust_settlement_average_amount'];//结算调整金额
            $editAchievement->settlement_average_amount = $arr['settlement_average_amount'];//结算分摊金额

            $editAchievement->origin_product_average_amount = $arr['origin_product_average_amount'];//原产品租金分摊金
            $editAchievement->adjust_product_average_amount = $arr['adjust_product_average_amount'];//产品租金调整金额
            $editAchievement->product_average_amount = $arr['product_average_amount'];//产品租金分摊金额

            $editAchievement->origin_sign_average_amount = $arr['origin_sign_average_amount'];//原签约分摊金额
            $editAchievement->adjust_sign_average_amount = $arr['adjust_sign_average_amount'];//签约调整金额
            $editAchievement->sign_average_amount = $arr['sign_average_amount'];//签约分摊金额

            $res = $editAchievement->save();

            return $res?$editAchievement->attributes['contract_application_id']:false;

        }

        if($arr['__type'] === 'add' && empty($contract)) {//通过授权增加

            if(!empty($arr['author_id'])) {//租户中管理过来

                if(empty($arr['contract_application_id'])){//云建要加的逻辑 如小蜜蜂
                    return true;
                }

                $priceInfo = ApplicationPriceRepository::getApplicationPriceByApplicationId($arr['application_id']);
                $price = $priceInfo['price'];

                $addAchievement->id = StringHelper::uuid();
                $addAchievement->contract_application_id = $arr['contract_application_id']; //这个要补充给我
                $addAchievement->contract_id = $arr['contract_id'];

                // 通过CPI 取appid
                $contractAndApp = ContractApplicationRepository::getContractApplicationAppId($arr['contract_application_id']);//订单产品信息

                //坏味道修复

                $addAchievement->application_id = $contractAndApp->application_id;

                $addAchievement->authorization_numeric = (int)$arr['total_num'];
                $addAchievement->settlement_type = $arr['settlement_type'];//结算类型
                $addAchievement->settlement_scale = $arr['settlement_scale'];//结算比例
                $addAchievement->discount = $arr['discount'];//结算比例
                $addAchievement->contract_type = $arr['contract_type'];
                $addAchievement->rent_period = $arr['rent_period'];
                $addAchievement->created_type = 2;//自动开通授权产生业绩
                $addAchievement->is_del = 1;//表示新增 记得原来的数据有可能为空预留给他们
                $addAchievement->application_name = $arr['friendly_name'];//产品名称
                //$addAchievement->establish_time = $arr['establish_time'];//开通时间 判断是否为历史数据
                $addAchievement->establish_time = date("Y-m-d" ,time());

                //坏味道修复

                $addAchievement->origin_settlement_average_amount = empty($arr['settlement_from_tenant'])?0:$arr['settlement_from_tenant'];//原结算分摊金
                $addAchievement->settlement_average_amount = empty($arr['settlement_from_tenant'])?0:$arr['settlement_from_tenant'];

                $addAchievement->origin_product_average_amount = $arr['product_average_amount'];//原产品分摊金
                $addAchievement->product_average_amount = $arr['product_average_amount'];

                $addAchievement->origin_sign_average_amount = $arr['sign_average_amount'];//原签约分摊金
                $addAchievement->sign_average_amount = $arr['sign_average_amount'];

                //坏味道修复

                $addAchievement->author_id = $arr['author_id'];//记录授权id方便通过授权修改 主要是not null 原因  //用于修改查询

                $addAchievement->amount = $price*(int)$arr['total_num'];//计算标准总额

                $res = $addAchievement->save();

                return $res?$addAchievement->attributes['id']:false;

            }


            $addAchievement->id = StringHelper::uuid();
            $addAchievement->contract_application_id = $arr['contract_application_id'];
            $addAchievement->contract_id = $arr['contract_id'];

            $addAchievement->application_id = $arr['application_id'];

            $addAchievement->price = $arr['price'];
            $addAchievement->authorization_numeric = (int)$arr['total_num'];
            $addAchievement->settlement_type = $arr['settlement_type'];
            $addAchievement->contract_type = $arr['contract_type'];
            $addAchievement->settlement_scale = $arr['settlement_scale'];
            $addAchievement->discount = $arr['discount'];
            $addAchievement->rent_period = $arr['rent_period'];
            $addAchievement->amount = $arr['amount'];

            $addAchievement->origin_settlement_average_amount = $arr['settlement_average_amount'];//原结算分摊金
            $addAchievement->settlement_average_amount = $arr['settlement_average_amount'];

            $addAchievement->origin_product_average_amount = $arr['product_average_amount'];//原产品分摊金
            $addAchievement->product_average_amount = $arr['product_average_amount'];

            $addAchievement->origin_sign_average_amount = $arr['sign_average_amount'];//原签约分摊金
            $addAchievement->sign_average_amount = $arr['sign_average_amount'];

            $addAchievement->created_type = 1;//手动开通授权产生业绩
            $addAchievement->is_del = 1;//表示新增 记得原来的数据有可能为空预留给他们
            $addAchievement->application_name = $arr['application_name'];//产品名称
            $addAchievement->establish_time = $arr['establish_time'];//开通时间 判断是否为历史数据

            // 貌似这里两个通过租户中心过来会没有$addAchievement->author_id
            $addAchievement->contractId = $arr['contractId'];//配置库那个 确定与授权关系
            // 不传id会报错
            $addAchievement->author_id = $arr['AuthorId'];//记录授权id方便通过授权修改 主要是not null 原因  //用于修改查询

            $res = $addAchievement->save();

            return $res?$addAchievement->attributes['id']:false;

        }


        if($arr['__type'] === 'add' && !empty($contract)) {//通过业绩增加

            $addAchievement->id = StringHelper::uuid();

            $addAchievement->contract_application_id = isset($arr['contract_application_id'])?$arr['contract_application_id']:'';//业绩信息直接增加导致没有这个id
            $addAchievement->contract_id = is_array($contract)?$contract['contract_id']:$contract;//业绩信息直接增加所以是这个值

            $addAchievement->contractId = $arr['contractId'];//业绩信息直接增加导致没有这个id

            $addAchievement->application_id = $arr['application_id'] == 'other'?$arr['other_application_id']:$arr['application_id'];

            $addAchievement->is_standard = 0;//业绩信息直接增加导致是非标

            $addAchievement->price = $arr['price'];
            $addAchievement->authorization_numeric = $arr['authorization_numeric'];//业绩信息直接增加所以是这个值
            $addAchievement->settlement_type = $arr['settlement_type'];
            $addAchievement->contract_type = $arr['contract_type'];
            $addAchievement->settlement_scale = $arr['settlement_scale'];
            $addAchievement->discount = $arr['discount'];
            $addAchievement->rent_period = $arr['rent_period'];
            $addAchievement->amount = $arr['amount'];

            // 云客类合同 需要别的规则计算结算分摊金
            if($arr['contract_nature'] == 'yks'){//云客类合同

                //坏味道修复

                $arr['standard_amount_all'] = empty($arr['standard_amount_all'])?1:$arr['standard_amount_all'];
                $arr['settlement_average_amount'] = (int)$arr['amount']/(int)$arr['standard_amount_all']*(int)$arr['balance_amount'];//标准总额占比*收入金额
                $arr['product_average_amount'] = (int)$arr['amount']/(int)$arr['standard_amount_all']*(int)$contractModel->rent_amount;//标准总额占比*收入金额
                $arr['sign_average_amount'] = (int)$arr['amount']/(int)$arr['standard_amount_all']*(int)$contractModel->sign_amount;//标准总额占比*收入金额

                $addAchievement->establish_time = $contractModel->input_date;//云客合同开通时间等于录入时间

                $arr['origin_settlement_average_amount'] = $arr['settlement_average_amount'];
                $arr['origin_product_average_amount'] = $arr['product_average_amount'];
                $arr['origin_sign_average_amount'] = $arr['sign_average_amount'];

            }

            $addAchievement->origin_settlement_average_amount = $arr['origin_settlement_average_amount'];//原结算分摊金
            $addAchievement->adjust_settlement_average_amount = $arr['adjust_settlement_average_amount'];//结算调整金额
            $addAchievement->settlement_average_amount = empty($arr['settlement_average_amount'])?0:$arr['settlement_average_amount'];

            $addAchievement->origin_product_average_amount = $arr['origin_product_average_amount'];//原产品分摊金
            $addAchievement->adjust_product_average_amount = $arr['adjust_product_average_amount'];//产品租金调整金额
            $addAchievement->product_average_amount = empty($arr['product_average_amount'])?0:$arr['product_average_amount'];


            $addAchievement->origin_sign_average_amount = $arr['origin_sign_average_amount'];//原签约分摊金
            $addAchievement->adjust_sign_average_amount = $arr['adjust_sign_average_amount'];//签约调整金额
            $addAchievement->sign_average_amount = empty($arr['sign_average_amount'])?0:$arr['sign_average_amount'];

            $addAchievement->created_type = 1;//手动开通授权产生业绩
            $addAchievement->is_del = 1;//表示新增 记得原来的数据有可能为空预留给他们
            $addAchievement->application_name = $arr['application_name'];//产品名称

            //坏味道修复

            $res = $addAchievement->save();

            return $res?$addAchievement->attributes['contract_application_id']:false;

        }


    }




    /**
     * 更新字段
     * @param $id
     * @param $data
     */
    public static function updatedByPk($id, $data)
    {
        return AuthorizationAchievementEntity::updateAll($data, "contract_application_id=:id", [":id" => $id]);
    }


    /**
     * 更新字段
     * @param $id
     * @param $data
     */
    public static function deleteAllByContractId($contractId)
    {
        return AuthorizationAchievementEntity::deleteAll(["contract_id" =>$contractId]);
    }


    /**
     * 获取业绩
     * @param $id
     * @param $data
     */
    public static function getAuthorizationAchievementByContractId($contractId)
    {
        return AuthorizationAchievementEntity::find()
            ->select("*,myscrm_authorization_achievement.application_id as app_id,myscrm_application_price.price as price_standard")
            //->where(['contract_id' => $contractId,'is_del' => 1])
            ->leftJoin("myscrm_application_info",
                "myscrm_application_info.application_id =myscrm_authorization_achievement.application_id")
            ->leftJoin("myscrm_application_price",
                "myscrm_application_info.application_id =myscrm_application_price.application_id")
            ->where(
                ['and' ,
                    ['=' , 'contract_id' , $contractId] ,
                    ['or' ,
                        ['=' , 'is_del' , 1] ,
                        ['is_del' => null]
                    ]
                ]
            )
            ->asArray()
            ->all();

    }

    /**
     * 通过授权获取业绩
     * @param $id
     * @param $data
     */
    public static function getAuthorizationAchievementByAuthorId($authorId)
    {
        return AuthorizationAchievementEntity::find()->select('*')->where(['author_id'=>$authorId])->all();
    }


    public static function handleAchievementData($contractId, $productArr)
    {
        if (empty($productArr)) {//没有产品，直接返回
            return true;
        }
    }


}